package com.vision.world.survey.tools;

import com.esri.arcgisruntime.geometry.Geometry;
import com.esri.arcgisruntime.geometry.GeometryType;
import com.esri.arcgisruntime.geometry.ImmutablePart;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.Polygon;

import java.io.IOException;
import java.util.Iterator;

/**
 * Created by Administrator on 2017/10/23.
 */

public class PolygonTools {

    /**
     * 判断点是否在多边形内
     *
     * @param point
     * @return
     * @throws IOException
     */
    public static boolean Contains(Point point, Geometry polygonGeo) throws IOException {
        boolean result;
        Polygon p = (Polygon) polygonGeo;
        ImmutablePart part = p.getParts().get(0);
        Iterator<Point> pointIterator = part.getPoints().iterator();
        int length = part.getPointCount();
        Point[] points = new Point[length];
        int i = 0;
        while (pointIterator.hasNext()) {
            points[i] = pointIterator.next();
            i++;
        }
        result = Point_In_Polygon(point, points);
        return result;
    }

    public static boolean Point_In_Polygon(Point p, Point[] polygonPS) {
        boolean bResult = false;
        int var5 = 0;
        for (int var6 = polygonPS.length - 1; var5 < polygonPS.length; var6 = var5++) {
            if ((polygonPS[var5].getY() <= p.getY() && p.getY() < polygonPS[var6].getY() || polygonPS[var6].getY() <= p.getY() && p.getY() < polygonPS[var5].getY()) && p.getX() < (polygonPS[var6].getX() - polygonPS[var5].getX()) * (p.getY() - polygonPS[var5].getY()) / (polygonPS[var6].getY() - polygonPS[var5].getY()) + polygonPS[var5].getY()) {
                bResult = !bResult;
            }
        }

        return bResult;
    }



    public static double pointToPolygons(Point point, Geometry polygonGeo){
        double result;
        Polygon p = (Polygon) polygonGeo;
        ImmutablePart part = p.getParts().get(0);
        Iterator<Point> pointIterator = part.getPoints().iterator();
        result=Point_Dis_Points(point,pointIterator);
        return result;
    }
    /**
     * 点到点集合的最短距离
     * @param p
     * @param pointIterator
     * @return
     */
    public static double Point_Dis_Points(Point p, Iterator<Point> pointIterator) {
        double dis = -1;
        double temp = 0;
        Point pointTemp;
        if (pointIterator.hasNext()) {
            pointTemp = pointIterator.next();
            dis = dis_Point_To_Point(p, pointTemp);
        }
        while (pointIterator.hasNext()) {
            pointTemp = pointIterator.next();
            temp = dis_Point_To_Point(p, pointTemp);
            if (temp < dis) {
                dis = temp;
            }
        }
        return dis;
    }

    public static double dis_Point_To_Point(Point p1, Point p2) {
        double resultDis = 0;
        resultDis = Math.sqrt(Math.pow((p1.getX() - p2.getX()), 2) + Math.pow((p1.getY() - p2.getY()), 2));
        return resultDis;
    }

}
